﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Core.DMS;

namespace Core.DMS.Providers
{
    public class DMSFileSystemMapProvider : SiteMapProvider
    {
        public override SiteMapNode FindSiteMapNode(string rawUrl)
        {
            string[] urlParts = rawUrl.Split("/".ToArray());
            int id = -1;
            int.TryParse(urlParts[urlParts.Length-1], out id);
            Folder info = Folder.Get(id);
            return CreateFromFolder(info);
        }

        public override SiteMapNodeCollection GetChildNodes(SiteMapNode node)
        {
            Folder nodeFolder = Folder.Get(int.Parse(node.Key));
            SiteMapNodeCollection results = new SiteMapNodeCollection();
            foreach (FileSystemObject child in nodeFolder)
            {
                if(child is Folder)
                    results.Add(CreateFromFolder(child as Folder));
            }

            return results;
        }

        public override SiteMapNode GetParentNode(SiteMapNode node)
        {
            if (node.Key == "-1")
                return null;

            return CreateFromFolder(Folder.Get(int.Parse(node.Key)));
        }

        protected override SiteMapNode GetRootNodeCore()
        {
            return CreateFromFolder(Folder.Root);
        }

        SiteMapNode CreateFromFolder(Folder info)
        {
            if (info != null)
            {
                SiteMapNode node = new SiteMapNode(this, info.ID.ToString());
                node.Title = info.Title;
                node.Url = "Folder/" + info.ID;
                return node;
            }

            return null;
        }
    }
}
